<?php
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');
class KalturaModelEntries extends JModel
{
    var $_data;
    var $_pagination;
    var $_ks;
    var $_client;
    
    var $_kalturapager;
    var $_kalturafilter = null;
    
    var $_instance_id;
    
    var $_fieldslist;
    var $_values;
    
    function __construct() 
    {
        parent::__construct();
		global $mainframe, $option;
		$limit = $mainframe->getUserStateFromRequest('global.list.limit','limit',$mainframe->getCfg('list_limit'), 'int');
		$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
		
		$this->_kalturapager = new KalturaFilterPager();
		
		$this->_kalturapager->pageIndex = $limitstart / $limit;
		$this->_kalturapager->pageSize = $limit;
		
		if (JRequest::getVar('freesearch')) {
		    $this->_kalturafilter = new KalturaBaseEntryFilter();
		    $this->_kalturafilter->searchTextMatchOr = 
		        JRequest::getVar('freesearch');
		}
		
		$partner_id = 100;
		$config = new KalturaConfiguration($partner_id);
		$config->serviceUrl = 'http://streamservice.eurotvguild.com';
		$this->_client = new KalturaClient($config);
		$secret = '129270d084b7d64abd2f9ea1a9ba9145';
		$type = KalturaSessionType::ADMIN;
		
		$this->_ks = $this->_client->session->start($secret, null, $type, 
		                                            $partner_id, null, null);
		                                     
		$this->_client->setKs($this->_ks);
		
		$this->_instance_id = JRequest::getVar('iid');
    }
    
    function getPagination() {
		if (empty($this->_pagination)) {
		    jimport('joomla.html.pagination');
		    $this->_pagination = 
		        new JPagination($this->getTotal(),
  		                        $this->getState('limitstart'), 
  		                        $this->getState('limit'));
    	}
		return $this->_pagination;
	}
    
    function getFieldsList() {
        if (empty($this->_fieldslist)) {
            $query = 'select * from #__Kaltura_fields where field_temp=0';
            $this->_db->setQuery($query);
            $this->_fieldslist = $this->_db->loadObjectList();
        }
        return $this->_fieldslist;
    }
    
    function getFieldValues($field_id) {
        $query = 'select * from #__Kaltura_fields_values where field_id='.$field_id;
        $this->_db->setQuery($query);
        return $this->_db->loadObjectList();
    }
    
    function getTotal() {
        $this->getEntries();
        return $this->_data->totalCount;
    }
    
    function getEntries() {
        if (!$this->_data)
            $this->_data = 
                $this->_client->baseEntry->listAction($this->_kalturafilter, 
                                                      $this->_kalturapager);
        foreach ($this->_data->objects as &$entry) {
            $query = 'select * from #__Kaltura_entry_cdata ';
            $query .= 'where kentry_id="'.$entry->id.'"';
            
            $this->_db->setQuery($query);
            $obj = $this->_db->loadObject();
            
            if ($obj)
                $entry->visible = $obj->kentry_visible;
        }
        return $this->_data;
    }
    
    function getValue($kentry_id, $field_id) {
        $query = 'select * from #__Kaltura_entry_field_value where ';
        $query .= 'kentry_id="'.$kentry_id.'" and field_id='.$field_id;
        echo $this->_db->setQuery($query);
        $value = $this->_db->loadObject();
        if ($value)
            return $value->value;
        else null;
    }
    
    function getValues($kentry_id) {
        $query = 'select * from #__Kaltura_entry_field_value where kentry_id="'.$kentry_id.'"';
        $this->_db->setQuery($query);
        $values = $this->_db->loadObjectList();
        
        $result = array();
        foreach($values as $val) {
            $result[$val->field_id] = $val->value;
        }
        
        return $result;
    }
    
    function setValue($kentry_id, $field_id, $value) {
        $query = 'select * from #__Kaltura_entry_field_value where ';
        $query .= 'kentry_id="'.$kentry_id.'" and field_id='.$field_id;
        
        $this->_db->setQuery($query);
        if (count($this->_db->loadObjectList()) > 0) {
            $query = 'update #__Kaltura_entry_field_value set value="'.$value.'"';
            $query .= ' where kentry_id="'.$kentry_id.'" and field_id='.$field_id;
        } else {
            $query = 'insert into #__Kaltura_entry_field_value (kentry_id, field_id, value)';
            $query .= ' values ("'.$kentry_id.'", '.$field_id.', "'.$value.'")';
        }
        $this->_db->setQuery($query);
        $this->_db->query();
        return $value;
    }
    
    function setDescription($entry_id, $value) {
        $query = 'update entry set description="'.$value.'" where id="'.$entry_id.'"';
        $edb =& ExternalDatabase::getDatabaseInstance($this->_instance_id);
        $edb->setQuery($query);
        $edb->query();
        return $value;
    }
    
    function setName($entry_id, $value) {
        $query = 'update entry set name="'.$value.'" where id="'.$entry_id.'"';
        $edb =& ExternalDatabase::getDatabaseInstance($this->_instance_id);
        $edb->setQuery($query);
        $edb->query();
        return $value;
    }
    
    function sync($iid) {
        $edb =& ExternalDatabase::getDatabaseInstance($iid);
        
        $query = 'select * from #__Kaltura_instances where id='.$iid;
        $this->_db->setQuery($query);
        $instance = $this->_db->loadObject();
        
        // update remote data with local data
        $query = 'select * from #__Kaltura_entry_cdata';
        $this->_db->setQuery($query);
        $local_entries = $this->_db->loadObjectList();
        
        foreach ($local_entries as $entry) {
            $query = 'update entry set ';
            $query .= 'name="'.$entry->kentry_name.'", ';
            $query .= 'description="'.$entry->kentry_description.'", ';
            $query .= 'where id="'.$entry->kentry_id.'"';
            
            $edb->setQuery($query);
            echo $edb->getQuery()."\n";
            $edb->query();
        }
        
        // populate entries
        $edb->setQuery('select * from entry where partner_id='.$instance->userid);
        $entries = $edb->loadObjectList();
        
        foreach ($entries as $entry) {
            $query = 'select count(*) from #__Kaltura_entry_cdata';
            $query .= ' where kentry_id='.$entry->id;
            $this->_db->setQuery($query);
            echo $this->_db->getQuery()."\n";
            
            if ($this->_db->loadResult() == 0) {
                $query = 'insert into #__Kaltura_entry_cdata(kentry_id, ';
                $query .= 'kentry_name, kentry_type, kentry_media_type, ';
                $query .= 'kentry_data, kentry_thumbnail, kentry_views, ';
                $query .= 'kentry_votes, kentry_status, kentry_source, ';
                $query .= 'kentry_length_in_msecs, kentry_created_at, ';
                $query .= 'kentry_updated_at, kentry_partner_id, kentry_site_url, ';
                $query .= 'kentry_plays, kentry_description, kentry_media_date, ';
                $query .= 'kentry_moderation_status, kentry_moderation_count, ';
                $query .= 'kentry_modified_at, kentry_categories, ';
                $query .= 'kentry_categories_ids, kentry_start_date, ';
                $query .= 'kentry_end_date, kentry_available_from) values ("'.$entry->id.'", ';
                $query .= '"'.$entry->name.'", '.$entry->type.', '.$entry->media_type.', ';
                $query .= '"'.$entry->data.'", "'.$entry->thumbnail.'", ';
                $query .= $entry->views.', '.$entry->votes.', '.$entry->status.', ';
                $query .= '"'.$entry->source.'", '.$entry->length_in_msecs.', ';
                $query .= '"'.$entry->created_at.'", "'.$entry->updated_at.'", ';
                $query .= $entry->partner_id.', "'.$entry->site_url.'", ';
                $query .= $entry->plays.', "'.$entry->description.'", ';
                $query .= '"'.$entry->media_date.'", '.$entry->moderation_status.', ';
                $query .= $entry->moderation_count.', "'.$entry->modified_at.'", ';
                $query .= '"'.$entry->categories.'", "'.$entry->categories_ids.'", ';
                $query .= '"'.$entry->start_date.'", "'.$entry->end_date.'", ';
                $query .= '"'.$entry->available_from.'")';
            }
            
            $this->_db->setQuery($query);
            echo $this->_db->getQuery()."\n";
            $this->_db->query();
        }
    }
    
    function toggleVisible($entry_id) {
        $query = 'select * from #__Kaltura_entry_cdata where kentry_id="'.$entry_id.'"';
        $this->_db->setQuery($query);
        $entry = $this->_db->loadObject();
        
        if ($entry) {
            if ($entry->kentry_visible == 1) {
                $query = 'update #__Kaltura_entry_cdata set kentry_visible=0 where kentry_id="'.$entry_id.'"';
            } else
                $query = 'update #__Kaltura_entry_cdata set kentry_visible=1 where kentry_id="'.$entry_id.'"';
            $this->_db->setQuery($query);
            $this->_db->query();
            return !($entry->kentry_visible);
        }
    }
}
?>
